package com.example.onlinetaxi.Thread;

import com.example.onlinetaxi.LocalStroage.LocalStorage;
import com.example.onlinetaxi.callback.DriverCallBack.ICancelCallBack;
import com.example.onlinetaxi.dto.DataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.GetDataResponse;
import com.example.onlinetaxi.util.OKHttpUtil.HttpUrl;
import com.example.onlinetaxi.util.OKHttpUtil.OKHttpUtil;

import java.util.HashMap;
import java.util.Map;

public class IsDriverAgreeCancelThread {
    // 创建线程
    public static Thread thread = null;

    public static boolean finished = false;

    public static ICancelCallBack iCancelCallBack = null;

    // 用来发送判断乘客是否取消的请求
    public static class GetOrderState implements Runnable {

        private String cancelState;

        @Override
        public void run() {
            // 轻微沉睡，保证订单被传送到
            try {
                Thread.sleep(1500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            // 存入订单id
            Map<String, String> map = new HashMap<>();
            map.put("orderId", LocalStorage.currentOrder.getReceivedOrderId().toString());

            // 使用while循环不断向后端发送订单状态获取信息
            while (true) {
                String response = OKHttpUtil.postAsyncRequest(HttpUrl.getBaseUrl(), map, "receivedOrder", "isAgree");

                DataResponse dataResponse = GetDataResponse.getDataResponse(response);

                if (LocalStorage.currentOrderId == null) {
                    break;
                }

                // 如果订单状态为receiver/completed
                if (dataResponse.getCode().equals("200")) {
                    // 请求成功
                    if (dataResponse.getData().containsKey("cancelState")) {
                        if (dataResponse.getData().get("cancelState").toString().equals("2")) {
                            // 取消成功
                            cancelState = "2";

                            break;
                        } else if (dataResponse.getData().get("cancelState").toString().equals("3")) {
                            // 取消失败
                            cancelState = "3";

                            break;
                        }
                    }
                }

                if (finished) {
                    break;
                }

                // 间歇800ms发一次
                try {
                    Thread.sleep(800);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }


            if (!finished) { // 用户没有取消
                // 在司机界面弹出用户取消理由的对话框
                if (cancelState.equals("2") || cancelState.equals("3")) {
                    // 执行回调函数，弹出对话框
                    iCancelCallBack.cancelCallBack(cancelState);
                }
            }

            // 销毁线程
            Thread.currentThread().interrupt();
        }
    }
}